import { Injectable } from '@angular/core';
import { StyleService } from './style.service';
import { MapService } from './map.service';
import * as wellknown from 'wellknown';
import * as  turf from '@turf/turf';
import { ToolService } from './tool.service';
import { LayerQueryService } from './layer.query.service';

@Injectable({
  providedIn: 'root'
})
export class LayerService {
  constructor(
    private styleService: StyleService,
    private toolService: ToolService,
    private layerQueryService: LayerQueryService,
    private mapService: MapService
  ) { }
  // 取线的第一个顶点
  getLineFirstPointCollection(geojson) {
    const result = {
      type: 'FeatureCollection',
      features: []
    };
    geojson.features.forEach(item => {
      const feature = {
        geometry: { type: 'Point', coordinates: item.geometry.coordinates[0][0] },
        properties: item.properties
      };
      result.features.push(feature);
    });
    return result;
  }
  getPropertyItem(dict, item) {
    const obj = {};
    dict.forEach(element => {
      Object.keys(item.property).forEach((key) => {
        if (element.fieldname === key) {
          obj[element.displayname] = this.dataFormat(item.property[key]);
        }
      });
    });
    return { title: item.title, property: obj };
  }
  dataFormat(value) {
    let pv;
    if (Number(value)) {
      pv = Math.round(Number(value) * 100) / 100;
    } else if (value === '0E-11') {
      pv = 0;
    } else {
      pv = value;
    }
    return pv;
  }
  // 取面要素中心点集合
  getPolygonCenterCollenction(geojson) {
    const result = {
      type: 'FeatureCollection',
      features: []
    };
    geojson.features.forEach(item => {
      let center = turf.center(item);
      center.properties = item.properties;
      result.features.push(center);
    });
    return result;
  }
  drawGeo(listData, mapbox, style = 'default') {
    if (!Array.isArray(listData)) {
      return;
    }
    const geojson: any = this.geoListToGeoJson(listData);
    if (!geojson.features) {
      return;
    }
    const geoType = turf.getType(geojson.features[0]);
    let zoomCenter: any = [];
    switch (geoType) {
      case 'Point':
        // const pagePointStyle = this.styleMapService.getStyleByflag(`${style}_point`, geojson);
        // this.apboxMapService.addGeoJSONLayer(pagePointStyle, {});
        zoomCenter = turf.center(geojson).geometry.coordinates;
        mapbox.flyTo({
          center: zoomCenter,
          zoom: 15,
        });
        break;
      case 'MultiLineString':
        const pageLinetyle = this.styleService.getStyleByflag(`${style}_line`, geojson);
        this.mapService.addGeoJSONLayer(pageLinetyle, {});
        const coordinate = geojson.features[0].geometry.coordinates[0];
        this.styleService.fitLineBounds(mapbox, coordinate);
        // zoomCenter = turf.center(geojson).geometry.coordinates;
        break;
      case 'MultiPolygon':
        const pagePolygontyle = this.styleService.getStyleByflag(`${style}_polygon`, geojson);
        this.mapService.addGeoJSONLayer(pagePolygontyle, {});
        const coordinates = geojson.features[0];
        this.styleService.getBoundingBox(geojson, mapbox);
        break;
      default:
        break;
    }
  }
  geoListToGeoJson(list) {
    const result = { type: 'FeatureCollection', features: [] };
    list.forEach((item, index) => {
      item.index = index + 1;
      // const geoItem = wellknown.parse(item.geo);
      result.features.push({ type: 'Feature', geometry: item.geometry, properties: item });
    });

    return result;
  }
  removeIQueryLayer() {
    const layers = this.styleService.getIQueryLayer();
    this.mapService.removeLayerByIds(layers);
  }
  removeLayerById() {
    const removeLayerID = this.styleService.getLayersIDlist();
    this.mapService.removeLayerByIds(removeLayerID);
  }
  // 返回一个要素集合对象
  getFeatureCollection(featureData) {
    return {
      type: 'FeatureCollection',
      features: featureData
    };
  }
  drawQuestionGeo(listData, style = 'question') {
    if (!Array.isArray(listData)) {
      return;
    }
    const pointFeature = this.geoSameToGeoJson(listData, 'Point');
    if (pointFeature.features.length > 0) {
      const pagePointStyle = this.styleService.getStyleByflag(`${style}_point`, pointFeature);
      this.mapService.addGeoJSONLayer(pagePointStyle, {});
    }
    // 暂时关闭线面
    // const lineFeature = this.geoSameToGeoJson(listData, 'LineString');
    // if (lineFeature.features.length > 0) {
    //   const pageLinetyle = this.styleMapService.getStyleByflag(`${style}_line`, lineFeature);
    //   this.apboxMapService.addGeoJSONLayer(pageLinetyle, {});
    // }
    // const PolygonFeature = this.geoSameToGeoJson(listData, 'Polygon');
    // if (PolygonFeature.features.length > 0) {
    //   const pagePolygontyle = this.styleMapService.getStyleByflag(`${style}_polygon`, PolygonFeature);
    //   this.apboxMapService.addGeoJSONLayer(pagePolygontyle, {});
    // }
  }
  geoSameToGeoJson(list, flag) {
    const result = { type: 'FeatureCollection', features: [] };
    list.forEach((item, index) => {
      const { type } = item.geometry;
      if (type === flag) {
        result.features.push(item);
      }
    });
    return result;
  }
  getLayerIdS(layeInfo) {
    const layerIDs = [];
    if (!Array.isArray(layeInfo)) {
      return;
    }
    layeInfo.forEach(element => {
      layerIDs.push({ layerId: element.sourceLayer, objId: element.id });
    });
    // const styleLayerID = layerIDs.join(',');
    return layerIDs;
  }
  // 绘制圆
  drawCircle(e, collback?) {
    // 返回回来的是一个要素数组，我们需要对其进行分类：点的放在一个集合里，线的放在一个集合里！
    const pointsData = [];
    const linesData = [];
    e.forEach(element => {
      const geojson = element.geometry;
      const { type } = geojson;
      switch (type) {
        case 'Point':
          pointsData.push(element);
          break;
        case 'MultiLineString':
          linesData.push(element);
          break;
        default:
          break;
      }
    });
    // 点要素添加到地图
    const style = 'hightlight';
    const pointsColl = this.getFeatureCollection(pointsData);
    // tslint:disable-next-line: no-shadowed-variable
    const pagePointStyle = this.styleService.getStyleByflag(`${style}_point`, pointsColl);
    this.mapService.addGeoJSONLayer(pagePointStyle, {});
    // 线要素高亮并加载到地图
    const linesColl = this.getFeatureCollection(linesData);
    const pageLinetyles = this.styleService.getStyleByflag('lightstyle_line', linesColl);
    this.mapService.addGeoJSONLayer(pageLinetyles, {});
    // collback(pointsData, linesData);
  }
  removeSameArr(items) {
    const obj = {};
    let item = items.reduce((cur, next) => {
      // tslint:disable-next-line:no-unused-expression
      obj[next.layer.id] ? '' : obj[next.layer.id] = true && cur.push(next);
      return cur;
    }, []);  // 设置cur默认类型为数组，并且初始值为空的数组
    return item;
  }
  formateDetail(dict) {
    if (dict.detail) {
      const detail = JSON.parse(dict.detail);
      const propertys = this.toolService.filterEnlishProperty(detail);
      return { title: dict.layerId, property: propertys };
    }
  }
  getSourceLayerList(data) {
    // 清空图层
    this.layerQueryService.clearLayer();
    data.forEach(element => {
      this.layerQueryService.setLayers(element.layerid);
    });
  }
  constroctroertiesList(mapbox, dict, e, callback) {
    const disctoryArr = [];
    dict.forEach(element => {
      const featureItem = this.formateDetail(element.properties);
      const itemFeature = { geo: element.geometry, itemData: featureItem };
      disctoryArr.push(itemFeature);
    });
    /// const point = this.styleMapService.mousePos(mapbox, e.originalEvent);
    callback(disctoryArr);
    // this.positionXY = point;
  }
  addLayerByType(e) {
    const { type } = e;
    switch (type) {
      case 'Point':
        const redPointStyle = this.styleService.getStyleByflag('iquery_point', e);
        this.mapService.addGeoJSONLayer(redPointStyle, {});
        break;
      case 'MultiLineString':
        const redLineStyle = this.styleService.getStyleByflag('iquery_line', e);
        this.mapService.addGeoJSONLayer(redLineStyle, {});
        break;
      default:
    }
  }
  getLayerItem(features) {
    const featuresItem = [];
    const searchLayer = this.layerQueryService.getLayers();
    if (!Array.isArray(features)) {
      return;
    }
    features.forEach(element => {
      if (searchLayer.includes(element.sourceLayer)) {
        featuresItem.push(element);
      }
    });
    return featuresItem;
  }
  getLayerName(arr, ele) {
    let Layername = '';
    const { id } = ele.layer;
    arr.forEach(element => {
      if (element.layerid.indexOf(id) > -1) {
        Layername = element.name;
      }
    });
    return Layername;
  }
  // todo处理图层名字
  getPropertysList(arr, features) {
    const propertyList = [];
    features.forEach(element => {
      const layerName = this.getLayerName(arr, element);
      propertyList.push({ title: layerName, property: element.properties });
    });
    return propertyList;
  }
  resetMapStyle() {
    const style = this.mapService.getMap().getStyle();
    this.mapService.getMap().flyTo({
      center: style.center,
      zoom: style.zoom,
      bearing: style.bearing || 0,
    });
  }
  // 选中列表项 定位
  searchListItemClick(item, mapboxglmap?) {
    this.removeLayerById();
    this.drawGeo([item], mapboxglmap);
  }
}
